package net.liteheaven.xblib.common.image;

import android.graphics.Bitmap;

import net.liteheaven.xblib.common.log.XLog;

import androidx.collection.LruCache;

public class BmpLruCache<T> {

    static private final String TAG = "BmpLruCache";
    static private void LOG(String str){
        XLog.i(TAG, str);
    }

    private LruCache<T, Bitmap> mMemoryCache = null;

    final static private float MAXMEMONRY = (int)(Runtime.getRuntime().maxMemory());

    public BmpLruCache(float percentage) {
        LOG("====> BmpLruCache, MAXMEMORY = "+MAXMEMONRY);
        mMemoryCache = new LruCache<T, Bitmap>((int)(MAXMEMONRY * percentage)) {
            @Override
            protected int sizeOf(T key, Bitmap bitmap) {
                // 重写此方法来衡量每张图片的大小，默认返回图片数量。
                return bitmap.getRowBytes() * bitmap.getHeight();
            }

            @Override
            protected void entryRemoved(boolean evicted, T key,
                                        Bitmap oldValue, Bitmap newValue) {
                LOG("hard cache is full , push to soft cache");
                if(oldValue != null && oldValue != newValue)
                {
                    if(!oldValue.isRecycled())
                    {
                        LOG("位图内存释放。");
                        oldValue.recycle();
                    }
                }
            }
        };
    }

    public synchronized void clear() {
        if (mMemoryCache != null) {
            if (mMemoryCache.size() > 0) {
                LOG("mMemoryCache.size() " + mMemoryCache.size());
                mMemoryCache.evictAll();
                LOG("mMemoryCache.size()" + mMemoryCache.size());
            }
        }
    }

    public synchronized void add(T key, Bitmap bitmap) {
        if (mMemoryCache.get(key) == null) {
            if (key != null && bitmap != null)
                mMemoryCache.put(key, bitmap);
        } else
            LOG("the res is aready exits");
    }

    public synchronized Bitmap get(T key, boolean once) {
        if (key != null) {
            Bitmap bm = mMemoryCache.get(key);
            if (once){
                mMemoryCache.remove(key);
            }
            if(bm != null && bm.isRecycled())
            {
                mMemoryCache.remove(key);
                return null;
            }
            return bm;
        }
        return null;
    }

    public synchronized void remove(T key) {
        if (key != null) {
            if (mMemoryCache != null) {
                Bitmap bm = mMemoryCache.remove(key);
                if (bm != null)
                    bm.recycle();
            }
        }
    }
}
